﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpDemo._04_泛型
{

    interface IDocument
    {
        string Title { get; set; }
        string Content { get; set; }
    }

    public class Document : IDocument
    {

        public string Title { get; set; }

        public string Content { get; set; }

        public Document(string Title, string Content)
        {
            this.Title = Title;
            this.Content = Content;
        }
    }



    //2.泛型的接口约束,泛型必须要实现某个接口或者继承某个类
    class DocumentManager<TDocument>
        where TDocument : IDocument
    {
        //3. 泛型类的静态成员只能在类的一个实例中共享
        public static int x;

        private readonly Queue<TDocument> documentQueue = new Queue<TDocument>();

        static DocumentManager() {
            x = 0;
        }
        public void AddDocument(TDocument document)
        {
            lock (this)
            {
                documentQueue.Enqueue(document);
            }
        }

        //1. Default关键字，定义泛型的默认值。
        //如果是引用类型默认值是null 。如果是基本类型，是基本类型的默认值.
        public TDocument GetDocument()
        {
            TDocument Document = default(TDocument);
            lock (this)
            {
                Document = documentQueue.Dequeue();
            }
            return Document;
        }

        //2.由于有接口的约束，导致每个队列中的每个元素都实现了IDocument接口,都有Title和Content属性
        public void ShowAllDocument()
        {
            foreach (TDocument Document in documentQueue)
            {
                IDocument o = (IDocument)Document;
                Console.WriteLine("Title:" + o.Title);
                Console.WriteLine("Content:" + o.Content);
            }
        }
    }


    public class GenericTest
    {
        public static void Test()
        {
            var dm = new DocumentManager<Document>();
            dm.AddDocument(new Document("Title A", "Content A"));
            dm.AddDocument(new Document("Title B", "Content B"));
            Console.WriteLine("\n泛型测试");
            dm.ShowAllDocument();
        }
    }
}
